package han.cirno.corrupt.activity.main

import android.content.Intent
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.core.view.WindowCompat
import dagger.hilt.android.AndroidEntryPoint
import han.cirno.corrupt.Application
import han.cirno.corrupt.activity.BaseActivity
import han.cirno.corrupt.compose.AppTheme
import han.cirno.corrupt.compose.LocalLocaleContext
import han.cirno.corrupt.data.SettingKeys
import han.cirno.corrupt.data.SettingLanguage
import han.cirno.corrupt.data.SettingOverrideNight
import han.cirno.corrupt.data.SettingRefreshFrequency
import han.cirno.corrupt.getPreferenceKey
import han.cirno.corrupt.writeDataStore
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.runBlocking
import java.util.Locale
import javax.inject.Inject

@AndroidEntryPoint
class MainActivity @Inject constructor(): BaseActivity() {
    private val viewModel: MainActivityViewModel by viewModels()

    lateinit var fileOpenLauncher: ActivityResultLauncher<Intent>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        this.enableEdgeToEdge()
        WindowCompat.setDecorFitsSystemWindows(window, false)
        setContent {
            val darkOverride by viewModel.configNightOverrideState.collectAsState()
            val legacy by viewModel.configLegacyColor.collectAsState()
            val language by viewModel.configLanguage.collectAsState()
            val localizedContext = remember(language) {
                Application.application.getLocaleContext(
                    when (language) {
                        SettingLanguage.CHINESE_SIMPLIFIED -> Locale.SIMPLIFIED_CHINESE
                        SettingLanguage.ENGLISH-> Locale.ENGLISH
                        SettingLanguage.NYA-> Locale("nya")
                        SettingLanguage.FOLLOW_SYSTEM-> Locale.getDefault()
                        else -> Locale.ENGLISH
                    }
                )
            }
            AppTheme(
                darkTheme = when (darkOverride) {
                    SettingOverrideNight.OVERRIDE_LIGHT -> false
                    SettingOverrideNight.OVERRIDE_DARK -> true
                    SettingOverrideNight.FOLLOW_SYSTEM -> isSystemInDarkTheme()
                    else -> isSystemInDarkTheme()
                },
                legacy = legacy) {
                CompositionLocalProvider(
                    LocalLocaleContext provides localizedContext) {
                    MainActivityLayout()
                }
            }
        }
        fileOpenLauncher=registerForActivityResult(ActivityResultContracts.StartActivityForResult()){
            viewModel.handleOpenedFile(it)
        }
    }

    override fun onResume() {
        super.onResume()
        val lastRefreshTime = runBlocking { viewModel.configLastRefreshTime.first() }
        val deltas=when(runBlocking { viewModel.configRefreshFrequency.first()}){
            SettingRefreshFrequency.ALWAYS->0L
            SettingRefreshFrequency.NEVER->System.currentTimeMillis()
            SettingRefreshFrequency.EVERY_5_MIN->5*60*1000L
            SettingRefreshFrequency.EVERY_10_MIN->10*60*1000L
            SettingRefreshFrequency.EVERY_30_MIN->30*60*1000L
            else->0L
        }
        if (System.currentTimeMillis()-deltas>=lastRefreshTime) {
            viewModel.refresh()
            runBlocking {
                writeDataStore(getPreferenceKey(SettingKeys.RAW_USER_LAST_REFRESH_TIME),System.currentTimeMillis())
            }
        }
    }
}